<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="评分" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入评分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 新增：患者姓名模糊查询 -->
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 新增：医生姓名查询 -->
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['comment:assess:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['comment:assess:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['comment:assess:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['comment:assess:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评价ID" align="center" prop="id" />
      <el-table-column label="评价内容" align="center" prop="content" />
      <el-table-column label="评分" align="center" prop="score" />
      <el-table-column label="医生回复" align="center" prop="reply" />
      <el-table-column label="评价时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 修改：显示患者姓名而非ID -->
      <el-table-column label="评价患者" align="center" prop="patientName" />
      <!-- 修改：显示医生姓名而非ID -->
      <el-table-column label="被评价医生" align="center" prop="doctorName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['comment:assess:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['comment:assess:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医生评价管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 新增：患者下拉选择 -->
        <el-form-item label="评价患者" prop="patientId">
          <el-select
            v-model="form.patientId"
            placeholder="请选择患者"
            clearable
            @change="handlePatientChange"
          >
            <el-option
              v-for="item in patientList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 新增：医生下拉选择 -->
        <el-form-item label="被评价医生" prop="doctorId">
          <el-select
            v-model="form.doctorId"
            placeholder="请选择医生"
            clearable
            @change="handleDoctorChange"
          >
            <el-option
              v-for="item in doctorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评价内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="医生回复">
          <editor v-model="form.reply" :min-height="192"/>
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-input v-model="form.score" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item label="评价时间" prop="time">
          <el-date-picker clearable
            v-model="form.time"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择评价时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAssess, getAssess, delAssess, addAssess, updateAssess } from "@/api/comment/assess"
// 引入患者和医生的接口（根据实际路径调整）
import { listPatient } from "@/api/doctor/patient"
import { listDoctor } from "@/api/doctor/doctor"

export default {
  name: "Assess",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医生评价管理表格数据
      assessList: [],
      // 患者列表（用于下拉框和名称匹配）
      patientList: [],
      // 医生列表（用于下拉框和名称匹配）
      doctorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数（新增患者姓名和医生姓名搜索条件）
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        content: null,
        score: null,
        reply:null,
        patientId: null,
        doctorId: null,
        patientName: null,  // 新增患者姓名搜索
        doctorName: null    // 新增医生姓名搜索
      },
      // 表单参数
      form: {
        id: null,
        content: null,
        score: null,
        reply:null,
        time: null,
        patientId: null,
        doctorId: null,
        patientName: null,  // 存储患者姓名
        doctorName: null,   // 存储医生姓名
        del: null
      },
      // 表单校验
      rules: {
        score: [
          { required: true, message: "评分不能为空", trigger: "blur" }
        ],
        time: [
          { required: true, message: "评价时间不能为空", trigger: "change" }
        ],
        patientId: [
          { required: true, message: "请选择评价患者", trigger: "change" }
        ],
        doctorId: [
          { required: true, message: "请选择被评价医生", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.loadPatientList()
    this.loadDoctorList()
  },
  methods: {
    /** 查询医生评价管理列表 */
    getList() {
      this.loading = true
      listAssess(this.queryParams).then(response => {
        // 为每条评价匹配患者和医生姓名
        this.assessList = response.rows.map(item => {
          const patient = this.patientList.find(p => p.id === item.patientId)
          const doctor = this.doctorList.find(d => d.id === item.doctorId)
          return {
            ...item,
            patientName: patient ? patient.name : '',
            doctorName: doctor ? doctor.name : ''
          }
        })
        this.total = response.total
        this.loading = false
      })
    },

    /** 加载患者列表（用于下拉框） */
    loadPatientList() {
      listPatient().then(response => {
        this.patientList = Array.isArray(response.rows) ? response.rows : []
      })
    },

    /** 加载医生列表（用于下拉框） */
    loadDoctorList() {
      listDoctor().then(response => {
        this.doctorList = Array.isArray(response.rows) ? response.rows : []
      })
    },

    /** 患者选择变化时更新名称 */
    handlePatientChange(patientId) {
      const patient = this.patientList.find(item => item.id === patientId)
      this.form.patientName = patient ? patient.name : ''
    },

    /** 医生选择变化时更新名称 */
    handleDoctorChange(doctorId) {
      const doctor = this.doctorList.find(item => item.id === doctorId)
      this.form.doctorName = doctor ? doctor.name : ''
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        content: null,
        score: null,
        reply:null,
        time: null,
        patientId: null,
        doctorId: null,
        patientName: null,
        doctorName: null,
        del: null
      }
      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加医生评价管理"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAssess(id).then(response => {
        this.form = response.data
        // 回显名称
        this.handlePatientChange(this.form.patientId)
        this.handleDoctorChange(this.form.doctorId)
        this.open = true
        this.title = "修改医生评价管理"
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAssess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAssess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

 // /** 删除按钮操作 */
  handleDelete(row) {
    const ids = row.id || this.ids
    this.$modal.confirm(`是否确认删除测评结果编号为"${ids}"的数据项？`).then(function() {
      return delAssess(ids)
   }).then(() => {
      this.getList()
      this.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  },
/** 删除按钮操作 */

    /** 导出按钮操作 */
  handleExport() {
      this.download('comment/assess/export', {
        ...this.queryParams
      }, `assess_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
